﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using SqlSugar;
using Zhao.AuthServer.JwtService;
using Zhao.Common;
using Zhao.Common.Helper;
using Zhao.IServer.Log;
using Zhao.IServer.User;
using Zhao.Models.DTO;

namespace Zhao.AuthServer
{
    /// <summary>
    /// 专属登录的，颁发token
    /// </summary>
    public static class AccountApiExt
    {
        public static void LoginApi(this WebApplication app)
        {

            app.MapPost("auto/Account", async ([FromServices]ILogsServer logs, [FromServices] CustomJWTService _iJWTService, [FromServices] ISqlSugarClient _Client, [FromServices]IAdminServer adminServer , LogInDto infoDto, HttpContext context) =>
            {

                var ipAddress = context.Connection.RemoteIpAddress.ToString();

                //查询数据库判断用户是否存在
                AdminInfoDto adminInfoDto =await adminServer.Login(infoDto.Account,MD5Encrypt.Encrypt(infoDto.Password), ipAddress);

                if (adminInfoDto == null)
                {

                    await logs.Info($"{infoDto.Account}登录失败");

                    return new ApiResult()
                    {
                        Success = true,
                        Message = "用户名或者密码错误"
                    };
                }

                string accessToken = _iJWTService.CreateToken(adminInfoDto, out string refreshtoken);

                await logs.Info($"{infoDto.Account}登录成功");

                return new ApiResult<object>()
                {
                    Success = true,
                    Message = "登录成功",
                    Data =new 
                    {
                        User= adminInfoDto,
                        RefreshToken= refreshtoken,
                        Token= accessToken
                    }
                };
            });


            ////刷新Token
            app.MapGet("auto/Account",
            [Authorize]
            ([FromServices] CustomJWTService _iJWTService, [FromServices] IMemoryCache _IMemoryCache, HttpContext context) =>
             {
                 //鉴权成功之后肯定能获取到guid
                 string refreshtokenGuid = context?.User?.FindFirst("refreshtokenGuid")?.Value;
                 if (string.IsNullOrWhiteSpace(refreshtokenGuid))
                 {
                     return new ApiResult()
                     {
                         Success = false,
                         Message = "已过期需要重新登录",
                     };
                 }
                 //直接取缓存 不需要进行数据库查询
                 AdminInfoDto adminInfo = _IMemoryCache.Get<AdminInfoDto>(refreshtokenGuid);
                 if (adminInfo == null)
                 {
                     return new ApiResult()
                     {
                         Success = false,
                         Message = "已过期需要重新登录",
                     };
                 }
                 //已经重新生成了两个token
                 string token = _iJWTService.CreateToken(adminInfo, out string refreshToken);
                 //删除之前存储的 
                 _IMemoryCache.Remove(refreshtokenGuid);
                 return new ApiResult<object>()
                 {
                     Success = true,
                     Message = "Token刷新成功",
                     Data =new
                     {
                         AccessToken = token,
                         RefreshToken = refreshToken
                     }
                 };
             }).WithGroupName("v1").WithDescription("刷新Token,使用RreshToken换新Token");

        }
    }
}
